package solution;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-01-18
 * Time: 16:53
 */
public class Solution5 {
    public static void main(String[] args) {
        String s = "a";
        String s1 = "abbcccffr";
        System.out.println(test4(s));
        System.out.println(test4(s1));
    }
    //例如： "aabbccdaa" -> "a2b2c2d1a2" 或者 例如： "abbcccffr" -> "a1b2c3f2r1"
    public static String test4(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        if (str.length() == 1) {
            return str + 1;
        }
        char[] chars = str.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < chars.length - 1; i++) {
            int count = 1;
            while (i < chars.length - 1 && chars[i] == chars[i + 1]) {
                count++;
                i++;
            }
            stringBuilder.append(chars[i]).append(count);
            if (i == chars.length - 1 - 1 && chars[i] != chars[i + 1]) {
                stringBuilder.append(chars[i + 1]).append(1);
            }
        }
        return stringBuilder.toString();
    }

    public static String test(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        char last = str.charAt(0);
        int count = 1;
        for (int i = 1; i < str.length(); i++) {
            if (str.charAt(i) == last) {
                count++;
            } else {
                stringBuilder.append(last).append(count);
                last = str.charAt(i);
                count = 1;
            }
        }
        stringBuilder.append(last).append(count);
        return stringBuilder.toString();
    }
}
